package moe.oil.db.api;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import moe.oil.db.service.ProfessionalService;
import moe.oil.dto.ProfessionalDTO;
import moe.oil.exception.professional.ProfessionalIdNullException;
import moe.oil.exception.professional.ProfessionalNameNullException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/19 16:59
 * Description:
 *
 * @author - -
 */
@RestController
@RequestMapping("/professional")
@Setter(onMethod_ = @Autowired)
@Log4j2
public class ProfessionalController {

    private ProfessionalService professionalService;

    // 根据id查询专业
    @GetMapping("/{id}")
    public ProfessionalDTO findByIdProfessional(@PathVariable("id") Long id) {
        return professionalService.selectProfessionalId(id).orElseThrow(() -> new ProfessionalIdNullException(id));
    }

    // 根据专业名查询
    @GetMapping("/query")
    public ProfessionalDTO findNameProfessional(@RequestBody ProfessionalDTO professionalDTO) {
        return professionalService.selectProfessionalName(professionalDTO.getProfessionalName()).orElseThrow(() -> new ProfessionalNameNullException(professionalDTO.getProfessionalName()));
    }

    // 查询全部专业
    @GetMapping("/{page}/{size}")
    public List<ProfessionalDTO> findAllProfessional(@PathVariable("page") int page, @PathVariable("size") int size) {
        return professionalService.selectProfessionalAll(PageRequest.of(page, size));
    }

    // 添加
    @PostMapping
    public ProfessionalDTO saveProfessional(@RequestBody ProfessionalDTO professionalDTO) {
        log.info("添加专业+\n\n" + professionalDTO);
        return professionalService.saveProfessional(professionalDTO).get();
    }

    // 根据ID删除专业
    @DeleteMapping("/{id}")
    public int deleteByIdProfessional(@PathVariable("id") Long id) {
        return professionalService.deleteProfessionalId(id);
    }

    // 修改
    @PutMapping
    public ProfessionalDTO updateProfessional(@Validated ProfessionalDTO professionalDTO) {
        return professionalService.updateProfessional(professionalDTO).get();
    }
}
